function playextract( avi, bfactor, treshold )
% playextract( avi, bfactor, trshold ) - extracts moving objects from background,
% and shows the process on player

% TODO use additional param to control style

% globals used by this method
global pe_background	% backgorund buffer (RGB, double)
global pe_movie			% movie
global pe_bfactor		% backgorund blending factor (param)
global pe_treshold		% object detection treshold (param)
global pe_detection_treshold	% how big part of screen has to be changed to trigger detection
global pe_detection_maxsize		% max stddev*3 of detected element


% get backgorund
pe_background = double( avi(1).cdata ) / 256;

% store params
pe_movie = avi;
pe_bfactor = bfactor;
pe_treshold = treshold;

% default params
pe_detection_treshold	= 0.003;
pe_detection_maxsize	= 200;


% run player
player( @pe_init, @pe_frame, 0 );


% ----------------- init player -------------------
function pe_init( p )

global player_frames pe_movie;
global pe_counter pe_rect pe_point;

player_frames = size( pe_movie, 2 );
pe_counter = text( 10,15, 'frame:', 'BackgroundColor', [1 1 1] );
pe_rect = line( 'Color', [0 1 0], 'Visible', 'off' );
pe_point = line('Marker', '+', 'Color', [0 0 1], 'Visible', 'off' ); 


% --------- frame display method -------
function pe_frame( p )

global player_current_frame pe_movie pe_background pe_treshold pe_bfactor pe_detection_treshold pe_detection_maxsize;
global pe_counter player_image pe_rect pe_point;

% current frame as double 
currentframe = double( pe_movie( player_current_frame ).cdata ) / 256;

% frame - backgorund diff
bkgnddiff = sum( abs( currentframe - pe_background ), 3 ) / 3;
fb = bkgnddiff > pe_treshold;

% foregroung coverage
coverage = sum(sum(fb)) / ( size( fb, 1 ) * size( fb, 2 ) );

% update background
pe_background = pe_background* (1-pe_bfactor) + double(currentframe) * pe_bfactor;

% diff analyze
%[mx,my,sx,sy] = statanalyze( fb );

% draw frame
% slow:
%image( pe_movie( player_current_frame ).cdata);
set( player_image, 'CData', pe_movie( player_current_frame ).cdata );

% show extra data
% slow
%text( 10, 15, num2str( player_current_frame ), 'BackgroundColor', [1 1 1] );
set( pe_counter, 'String', sprintf('frame: %.0f', player_current_frame ) ); 


% analyze if foreground coverage above trewshold
if coverage > pe_detection_treshold
	[mx,my,sx,sy] = statanalyze( fb );
	
	
	% paint rect?
	if sx*3 < pe_detection_maxsize && sy*3 < pe_detection_maxsize
		setrect( pe_rect, mx - sx*3, my-sy*3, sx*6, sy*6);
		set( pe_point, 'XData',  mx );
		set( pe_point, 'YData', my );
		set( pe_point, 'Visible', 'on' );
	end
else
	set( pe_point, 'Visible', 'off');
	set( pe_rect, 'Visible', 'off');
end

% --------------------- setting up line in a rect --------------------
function setrect( hline, x, y, w ,h )

outline = [ x y; x y+h; x+w y+h ; x+w y; x y ];

set( hline, 'XData', outline(:,1) );
set( hline, 'YData', outline(:,2) );
set( hline, 'Visible', 'on' );
